import 'package:flutter/material.dart';
import 'package:flutter_wisave/HomePage.dart';
import 'package:flutter_wisave/MessagesPage.dart';
import 'package:flutter_wisave/CentrePage.dart';
import 'package:flutter_wisave/SearchPage.dart';
import 'package:flutter_wisave/SettingsPage.dart';
import 'package:flutter_wisave/LoginPage/LoginPage.dart';
import 'package:flutter_wisave/widgets/AppColors.dart';
import '../Tools/ToolsLocalStorage.dart';
import '../Tools/NetworkService.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await AppColors.initTheme();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({super.key});

  static final GlobalKey<NavigatorState> navigatorKey =
      GlobalKey<NavigatorState>();

  // 新增静态方法
  static void updateSelectedIndex(int index) {
    final state = navigatorKey.currentState?.context
        .findAncestorStateOfType<_MyAppState>();
    state?.setState(() {
      state._selectedIndex = index;
    });
  }

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _selectedIndex = 0;

  void _onTabTapped(int index) {
    MyApp.updateSelectedIndex(index);
    print('onTap: $index');
    // 移除这个条件块，因为 TabBar 已经处理了页面切换
    // if (index == 2) {
    //   Navigator.push(
    //       context, MaterialPageRoute(builder: (context) => const CentrePage()));
    // }
  }

  Image _getTabIcon(int index, String selectedImage, String unselectedImage) {
    return Image.asset(
      _selectedIndex == index ? selectedImage : unselectedImage,
      width: 24,
      height: 24,
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: MyApp.navigatorKey,
      theme: ThemeData(
        brightness: Brightness.light,
        primaryColor: Color(0xFF2AB6F7),
        // 其他主题配置
      ),
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        primaryColor: Color(0xFF2AB6F7),
        // 其他暗主题配置
      ),
      themeMode: ThemeMode.system, // 根据系统设置切换主题
      home: FutureBuilder<String?>(
        future: LocalStorage.getstr('token'),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return CircularProgressIndicator(); // 显示加载指示器
          } else {
            final token = snapshot.data;
            if (token == null || token.isEmpty) {
              return LoginPage(); // 显示登录页
            } else {
              return DefaultTabController(
                length: 5,
                initialIndex: _selectedIndex, // 添加这行来设置初始选中的标签
                child: Scaffold(
                  backgroundColor: AppColors.backgroundColor,
                  body: TabBarView(
                    physics: NeverScrollableScrollPhysics(), // 禁用滑动切换
                    children: [
                      HomePage(),
                      SearchPage(),
                      CentrePage(),
                      MessagesPage(),
                      SettingsPage(),
                    ],
                  ),
                  bottomNavigationBar: SafeArea(
                    child: Padding(
                      padding: const EdgeInsets.only(bottom: 16.0), // 添加底部安全区域
                      child: TabBar(
                        indicatorColor: Colors.transparent,
                        tabs: [
                          Tab(
                            icon: _getTabIcon(
                                0,
                                'assets/images/tabbar/home.png',
                                'assets/images/tabbar/homeun.png'),
                            // text: "首页",
                            child: Container(
                              child: Text(
                                '首页',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 11),
                              ),
                            ),
                          ),
                          Tab(
                            icon: _getTabIcon(
                                1,
                                'assets/images/tabbar/cloudeyes.png',
                                'assets/images/tabbar/cloudeyesun.png'),
                            // text: "云眼",
                            child: Container(
                              child: Text(
                                '云眼',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 11),
                              ),
                            ),
                          ),
                          Tab(
                            icon: _getTabIcon(
                                2,
                                'assets/images/tabbar/Centre.png',
                                'assets/images/tabbar/Centre.png'),
                            child: Container(
                              child: Text(
                                '智控中心',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 11),
                              ),
                            ),
                          ),
                          Tab(
                            icon: _getTabIcon(
                                3,
                                'assets/images/tabbar/news.png',
                                'assets/images/tabbar/newsun.png'),
                            // text: "资讯",
                            child: Container(
                              child: Text(
                                '资讯',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 11),
                              ),
                            ),
                          ),
                          Tab(
                            icon: _getTabIcon(4, 'assets/images/tabbar/me.png',
                                'assets/images/tabbar/meun.png'),
                            // text: "我的",
                            child: Container(
                              child: Text(
                                '我的',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontSize: 11),
                              ),
                            ),
                          ),
                        ],
                        labelColor: Color(0xFF2AB6F7),
                        unselectedLabelColor: Color(0xFFB9C1D9),
                        onTap: _onTabTapped,
                      ),
                    ),
                  ),
                ),
              );
            }
          }
        },
      ),
    );
  }
}
